package net.csdn.business.notify.handler.handler.impl;



import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dm20151123.Client;
import com.aliyun.dm20151123.models.SingleSendMailRequest;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.constant.CommonConstants;
import net.csdn.business.notify.common.enums.NotifyChannel;
import net.csdn.business.notify.common.enums.RateLimitStrategy;
import net.csdn.business.notify.common.model.dto.UpdateNotifyRemindRecordDTO;
import net.csdn.business.notify.common.pipeline.domain.TaskInfo;
import net.csdn.business.notify.common.pipeline.model.EmailContentModel;
import net.csdn.business.notify.handler.service.INotifyAsyncService;
import net.csdn.business.notify.common.utils.StrUtils;
import net.csdn.business.notify.handler.config.NotifyHandlerConfigData;
import net.csdn.business.notify.handler.flowcontrol.FlowControlParam;
import net.csdn.business.notify.handler.handler.BaseHandler;
import net.csdn.business.notify.handler.utils.EmailPushConfigClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * @ClassName EmailHandler
 * @Description  邮件发送处理
 * @Author zhangyl
 * @Date 2023/11/30 18:23
 */
@Component
@Slf4j
public class EmailHandler extends BaseHandler {

    @Autowired
    private NotifyHandlerConfigData configData;

    @Autowired
    private INotifyAsyncService notifyAsyncService;


    public EmailHandler() {
        channelCode = NotifyChannel.EMAIL.getCode();
        Double rateInitValue = Double.valueOf(10);
        flowControlParam = FlowControlParam.builder().rateInitValue(rateInitValue)
                .rateLimitStrategy(RateLimitStrategy.REQUEST_RATE_LIMIT)
                .rateLimiter(RateLimiter.create(rateInitValue)).build();

    }

    @Override
    public boolean handler(TaskInfo taskInfo) {
        boolean result=false;
        String contenModel= taskInfo.getContentModel();
        EmailContentModel emailContentModel = JSONObject.parseObject(contenModel,EmailContentModel.class);
        String title=emailContentModel.getTitle();
        String content=emailContentModel.getContent();
        String batchNum=taskInfo.getBatchNum();
        String businessCode=taskInfo.getBusinessCode();
        Integer notifyChannel=taskInfo.getNotifyChannel();
        List<String> accounts=taskInfo.getAccounts();
        String addressStr = StringUtils.join(accounts, CommonConstants.COMMA);
        try {
            String accessKey = configData.getAccessKey();
            String accessSecret = configData.getAccessSecret();
            String senderAccount = configData.getSenderAccount();
            String senderAlias = configData.getSenderAlias();

            Client client = EmailPushConfigClient.getInstance(accessKey, accessSecret).getClient();
            if (client != null) {
                SingleSendMailRequest singleSendMailRequest = new SingleSendMailRequest()
                        .setAccountName(senderAccount) // 发信地址
                        .setAddressType(1)           // 0：随机账号 1：发信地址
                        .setReplyToAddress(false)    // 回信地址
                        .setToAddress(addressStr)    // 收信地址  1945917147@qq.com
                        .setSubject(StrUtils.substring(title, 100))         // 标题      用户注册-操作提醒
                        .setFromAlias(senderAlias)        // 邮件发送方 CSDN
                        .setHtmlBody(content);      // 尊敬的用户，您好：<br><br>&emsp;&emsp;您在 <b>"+ DateTime.now()+" </b>完成了注册，请您保管好账号及密码。如有疑问，请及时联系客服人员。<br><br>&emsp;&emsp;(这是一封自动发送的邮件，请不要直接回复)
                RuntimeOptions runtime = new RuntimeOptions();
                // 复制代码运行请自行打印 API 的返回值
                client.singleSendMailWithOptions(singleSendMailRequest, runtime);
                log.info("notify send email success:{}-----{}", title, addressStr);
                result=true;
            }
        } catch (Exception error) {
            log.error("notify send email fail {}-----{}----errorMsg:{}", title , addressStr,error.getMessage());
            result=false;
        }finally {
            //异步更新发送状态
            List<String> userAccount=taskInfo.getAccounts();
            try{
                UpdateNotifyRemindRecordDTO params=new UpdateNotifyRemindRecordDTO();
                params.setBatchNum(batchNum);
                params.setUserAccounts(userAccount);
                params.setBusinessCode(businessCode);
                params.setNotifyChannel(notifyChannel);
                if(result){
                    params.setNotifyState(1);
                    notifyAsyncService.updateSendStatusBatchAsync(params);
                }else{
                    params.setNotifyState(-1);
                    notifyAsyncService.updateSendStatusBatchAsync(params);
                }
            }catch (Throwable e){
                e.printStackTrace();
                log.info("email handler update send status error :{}",e.getMessage());
            }
        }
        return result;
    }


}
